package com.ssm.controller;

import com.ssm.entity.UserVo;
import com.ssm.service.UserService;
import com.ssm.utils.ExcelExport;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.List;

@RestController
@RequestMapping("/Excel")
public class ExcleController {

        @Autowired
        private UserService userService;

        @RequestMapping(value="/download")
        public @ResponseBody
        String dowm(HttpServletResponse response, @RequestParam("id") String id, @RequestParam("name") String name){
            response.setContentType("application/binary;charset=UTF-8");
            try{
                ServletOutputStream out=response.getOutputStream();
                try {
                    //设置文件头：最后一个参数是设置下载文件名(这里我们叫：张三.pdf)
                    response.setHeader("Content-Disposition", "attachment;fileName=" + URLEncoder.encode(name+".xls", "UTF-8"));
                } catch (UnsupportedEncodingException e1) {
                    e1.printStackTrace();
                }

                List<UserVo> list =  userService.queryAll();

                ExcelExport excelExport = new ExcelExport();

                String[] titles = { "用户id", "用户姓名", "用户密码", "用户年龄" };
                String[] valie = {"userId","name","password","age"};
                excelExport.export(titles, out,list);
                return "success";
            } catch(Exception e){
                e.printStackTrace();
                return "导出信息失败";
            }
        }
    }
